//
//  SEPrescriptionOrderDetailViewController.swift
//  SmartEyeForPatient
//
//  Created by qdsg on 2021/4/17.
//

import UIKit

class SEPrescriptionOrderDetailViewController: SEBaseViewController {

    var viewModel = SEPrescriptionOrderDetailViewModel()

    var paySuccessHandler: (() -> Void)?

    convenience init(prescriptionId: String) {
        self.init()
        self.viewModel.model.id = prescriptionId
    }


    @IBOutlet weak var tableViewBottomToSafeArea: NSLayoutConstraint!

    @IBOutlet weak var tableViewBottomToPayView: NSLayoutConstraint!


    @IBOutlet weak var payView: SEConfirmReservePayView! {
        didSet {
            payView.isHidden = true
            payView.delegate = self
        }
    }

    @IBOutlet weak var tableView: UITableView! {
        didSet {
            tableView.isHidden = true
            tableView.tableFooterView = UIView()
            tableView.register(UINib(nibName: SEHospitalizeOrderPatientCell.className, bundle: nil), forCellReuseIdentifier: SEHospitalizeOrderPatientCell.reuseId)
            tableView.register(UINib(nibName: SEHospitalizeOrderInfoCell.className, bundle: nil), forCellReuseIdentifier: SEHospitalizeOrderInfoCell.reuseId)
            tableView.register(UINib(nibName: SEPrescriptionOrderDrugCell.className, bundle: nil), forCellReuseIdentifier: SEPrescriptionOrderDrugCell.reuseId)
            tableView.register(UINib(nibName: SEPrescriptionOrderTimeCell.className, bundle: nil), forCellReuseIdentifier: SEPrescriptionOrderTimeCell.reuseId)
            tableView.register(UINib(nibName: SEPatientTitleTextFieldCell.className, bundle: nil), forCellReuseIdentifier: SEPatientTitleTextFieldCell.reuseId)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "订单详情"
        requestPrescriptionOrderDetail()
        // Do any additional setup after loading the view.
    }

    override func setupUI() {
        super.setupUI()

        viewModel.updateData = { status in
            switch status {
            case .success:
                self.reloadData()
            case .auth(let msg):
                self.presentLoginViewController(selector: #selector(self.requestPrescriptionOrderDetail)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.submitAddressHandler = { status in
            switch status {
            case .success:
                self.requestPayPrescriptionOrder()
            case .auth(let msg):
                self.presentLoginViewController(selector: #selector(self.requestSubmitPrescriptionOrderAddress)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.payHandler = { status in
            switch status {
            case .success:
                SEHUD.show(message: "支付成功")
                self.paySuccessHandler?()
                self.navigationController?.popViewController(animated: true)
            case .auth(let msg):
                self.presentLoginViewController(selector: #selector(self.requestPayPrescriptionOrder)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }
    }

    lazy var headerViewForSectionTwo: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.white
        let label = UILabel()
        label.text = "RP："
        label.textColor = Asset.textLight.color
        label.font = UIFont.regular(14)
        view.addSubview(label)
        label.snp.makeConstraints { (make) in
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.centerY.equalTo(view.snp.centerY)
        }
        return view
    }()

    func headerViewForSectionFour() -> UIView {
        let view = UIView()
        view.backgroundColor = Asset.background.color
        let label = UILabel()
        label.text = viewModel.model.orderStatus == .waitpay ? "填写配送地址" : "配送地址"
        label.font = UIFont.regular(13)
        label.textColor = Asset.textDark.color
        view.addSubview(label)
        label.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.centerY.equalTo(view.snp.centerY)
        }
        return view
    }

    lazy var footerViewForSectionTwo: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.white
        let feeView = SEPrescriptionOrderDrugFooterView()
        feeView.feeLabel.text = String(format: "%.2lf元", viewModel.model.totalExpense / 100.0)
        view.addSubview(feeView)
        feeView.snp.makeConstraints { (make) in
            make.margins.equalTo(0)
        }
        return view
    }()

    private func reloadData() {
//        if viewModel.model.orderStatus == .waitpay {
//            payView.isHidden = false
//            tableViewBottomToSafeArea.priority = .defaultLow
//            tableViewBottomToPayView.priority = .defaultHigh
//            payView.updateView(with: viewModel.payViewModel)
//        } else {
            payView.isHidden = true
            tableViewBottomToSafeArea.priority = .defaultHigh
            tableViewBottomToPayView.priority = .defaultLow
//        }
        tableView.isHidden = false
        tableView.reloadData()
    }

    private func showAgreementView() {
        let agreementView = UINib.loadViewFrom(AgreementAlertView.self)
                        agreementView.show(type: .informedLetter)
    }

    private func pushToChat() {
        var model = SEInquiryInfo()
        model.type = .online
        model.id = viewModel.model.bisId
        let vm = SEInquiryInfoViewModel(info: model)
        let vc = SEChatViewController(infoViewModel: vm)
        vc.title = viewModel.model.doctor
        navigationController?.pushViewController(vc, animated: true)
    }

    private func presentAddressController() {
        view.endEditing(true)
        let addressVc = AddressViewController()
        addressVc.modalPresentationStyle = .custom
        addressVc.chooseClosure = { model in
            self.viewModel.model.orderLogisticsDto.provideId = model.provinceId
            self.viewModel.model.orderLogisticsDto.provideName = model.provinceName
            self.viewModel.model.orderLogisticsDto.cityId = model.cityId
            self.viewModel.model.orderLogisticsDto.cityName = model.cityName
            self.viewModel.model.orderLogisticsDto.areaId = model.areaId
            self.viewModel.model.orderLogisticsDto.areaName = model.areaName
            self.tableView.reloadData()
        }
        present(addressVc, animated: true) {
            addressVc.view.backgroundColor = UIColor.black.withAlphaComponent(0.36)
        }
    }

}

// MARK: - UITableViewDataSource, UITableViewDelegate

extension SEPrescriptionOrderDetailViewController: UITableViewDataSource, UITableViewDelegate {

    // MARK: - UITableViewDataSource

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.numberOfRowsInSection(section: section)
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.numberOfSections
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEHospitalizeOrderPatientCell.reuseId, for: indexPath) as! SEHospitalizeOrderPatientCell
            cell.updateCell(viewModel)
            return cell
        }
        if indexPath.section == 1 {
            let model = viewModel.infoModelArray[indexPath.row]
            let cell = tableView.dequeueReusableCell(withIdentifier: SEHospitalizeOrderInfoCell.reuseId, for: indexPath) as! SEHospitalizeOrderInfoCell
            cell.updateCell(model: model)
            return cell
        }
        if indexPath.section == 2 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEPrescriptionOrderDrugCell.reuseId, for: indexPath) as! SEPrescriptionOrderDrugCell
            cell.updateData(viewModel.model.list[indexPath.row])
            return cell
        }
        if indexPath.section == 3 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEPrescriptionOrderTimeCell.reuseId, for: indexPath) as! SEPrescriptionOrderTimeCell
            cell.delegate = self
            cell.updateData(viewModel)
            return cell
        }
        if indexPath.section == 4 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEPatientTitleTextFieldCell.reuseId, for: indexPath) as! SEPatientTitleTextFieldCell
            cell.delegate = self
            cell.updateCell(model: viewModel.logisticsModelArray[indexPath.row], indexPath: indexPath)
            return cell
        }
        return UITableViewCell()
    }

    // MARK: - UITableViewDelegate

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 0: return 80
        case 4: return 50
        default: return UITableView.automaticDimension
        }
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        switch section {
        case 2: return headerViewForSectionTwo
        case 4: return headerViewForSectionFour()
        default: return UIView()
        }
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 2: return viewModel.model.list.count > 0 ? 30 : 0
        case 4: return 40
        default: return 0
        }
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return footerViewForSectionTwo
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        switch section {
        case 2: return viewModel.model.list.count > 0 ? 45 : 0
        default: return 0
        }
    }

}

// MARK: - SEPatientTitleTextFieldCell

extension SEPrescriptionOrderDetailViewController: SEPatientTitleTextFieldCellDelegate {
    func patientTitleTextFieldCellDidEndEdit(titleTextFieldCell: SEPatientTitleTextFieldCell, indexPath: IndexPath) {
        switch indexPath.row {
        case 0:
            viewModel.model.orderLogisticsDto.receiveName = titleTextFieldCell.textField.text!
        case 1:
            viewModel.model.orderLogisticsDto.receiveMobile = titleTextFieldCell.textField.text!
        case 2:
            presentAddressController()
        case 3:
            viewModel.model.orderLogisticsDto.receiverAddress = titleTextFieldCell.textField.text!
        default:
            SELog("default")
        }
    }

    func patientTitleTextFieldCellCodeBtnAction() {

    }
}

// MARK: - SEConfirmReservePayViewDelegate

extension SEPrescriptionOrderDetailViewController: SEConfirmReservePayViewDelegate {
    func confirmReservePayViewBtnAction(_ payView: SEConfirmReservePayView, with actionType: SEConfirmReservePayViewActionType) {
        switch actionType {
        case .agree:
            viewModel.isAgree = payView.agreeBtn.isSelected
            reloadData()
        case .showInfo:
            showAgreementView()
        case .pay:
            requestSubmitPrescriptionOrderAddress()
        }
    }
}

// MARK: - SEPrescriptionOrderTimeCellDelegate

extension SEPrescriptionOrderDetailViewController: SEPrescriptionOrderTimeCellDelegate {
    func prescriptionOrderTimeCellBtnAction() {
        pushToChat()
    }
}

// MARK: - APIRequest
extension SEPrescriptionOrderDetailViewController {
    @objc private func requestPrescriptionOrderDetail() {
        viewModel.requestPrescriptionDetail()
    }

    @objc private func requestSubmitPrescriptionOrderAddress() {
        viewModel.requestSubmitPrescriptionOrderAddress()
    }

    @objc private func requestPayPrescriptionOrder() {
        viewModel.requestPayPrescriptionOrder()
    }

}
